package program;

import hexgame.HexGame;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicBoolean;


public class GameManager {
	static List<HexGame> games = new ArrayList<HexGame>();
	static AtomicBoolean gameLock;
	
	Timer timer;
	
	public GameManager() {
		timer = new Timer();

		gameLock = new AtomicBoolean(false);
	}
	
	public void scheduleWindowGameCheck(TimerTask t) {
		timer.schedule(t,  0, 2000);
	}

	public static void addGame(HexGame game) {
		while(gameLock.get()) {
			// Shouldn't lock up for more than a few milliseconds every 1 second
		}
		games.add(game);
	}
	
	/**
	 * Gets the list of games. This list should be modified
	 * @param game
	 */
	public static List<HexGame> getGames() {
		while(gameLock.get()) {
			// Shouldn't lock up for more than a few milliseconds every 1 second
		}
		return games;
	}
	
	/**
	 * Gets the list of games. This list should be modified
	 * @param game
	 */
	public static void setGames(List<HexGame> newGames) {
		while(gameLock.get()) {
			// Shouldn't lock up for more than a few milliseconds every 1 second
		}
		gameLock.set(true);
		games = newGames;
		gameLock.set(false);
	}
	
	
	/**
	 * Waits for all games to finish, then returns the number of games won by the localhost
	 * @return number of games won by this program
	 */
	public int numGamesWon() {
		int numWon = 0;
		
		while(games.size() > 0) {
			try {
				Thread.sleep(1000);
			}
			catch (InterruptedException e) {
				return -1;
			}
			gameLock.set(true);
			
			ListIterator<HexGame> it = games.listIterator();
			while(it.hasNext()) {
				HexGame game = it.next();
				if(game.hasEnded()) { 
					if(game.hasLocalPlayerWon()) {
						numWon++;
					}
					it.remove();
				}
			}
			gameLock.set(false);
		}
		
		return numWon;
	}
	
}
